using System;
using System.Globalization;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;
using System.Xml;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace ArrowWebParts
{
    [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
    [SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true)]
    public class ArrowFeatureReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            // remove old .webpart files
            // from http://www.theblackknightsings.com/FeatureReceiverToCleanupWebPartFiles.aspx
            using (SPSite site = properties.Feature.Parent as SPSite)
                RemoveWebParts(site, properties.Definition);
        }

        /// <summary>
        /// Deletes the web part files from the web part gallery.
        /// </summary>
        /// <param name="site"></param>
        /// <param name="definition"></param>
        private void RemoveWebParts(SPSite site, SPFeatureDefinition definition)
        {
            using (SPWeb web = site.RootWeb)
            {
                string wpcatalogUrl = SPUrlUtility.CombineUrl(web.Url, "_catalogs/wp");

                // Get the Feature.xml for the feature
                XmlDocument featureXml = new XmlDocument();
                featureXml.LoadXml(definition.GetXmlDefinition(web.Locale).OuterXml);
                XmlNamespaceManager nsMgr = new XmlNamespaceManager(featureXml.NameTable);
                nsMgr.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/");

                // Get the Location attribute of each ElementManifest inside each ElementManifests inside the Feature
                foreach (XmlNode locationNode in featureXml.SelectNodes("/sp:Feature/sp:ElementManifests/sp:ElementManifest/@Location", nsMgr))
                {
                    // Get the ElementManifest XML
                    XmlDocument elementManifest = new XmlDocument();
                    elementManifest.Load(Path.Combine(definition.RootDirectory, locationNode.Value));
                    XmlNamespaceManager nsMgr2 = new XmlNamespaceManager(elementManifest.NameTable);
                    nsMgr2.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/");
                    
                    // Get the Url attribute of each file in Modules (with List attribute='113' WebPartCatalog
                    foreach (XmlNode webPartFileUrl in elementManifest.SelectNodes("/sp:Elements/sp:Module[@List='113']/sp:File/@Url", nsMgr2))
                    {
                        // Delete the file from the WebPart Catalog
                        SPFile wpFile = web.GetFile(SPUrlUtility.CombineUrl(wpcatalogUrl, webPartFileUrl.Value));
                        wpFile.Delete();
                    }
                }
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            
        }
    }
}